const dgram = require('dgram');
const WebSocket = require('ws');
const client = dgram.createSocket('udp4');
const BROADCAST_PORT = 8888;

let ws = null;

// 允许接收广播消息
client.bind(BROADCAST_PORT, () => {
    client.setBroadcast(true);
    console.log('UDP客户端已启动，正在监听广播消息...');
});

// 接收广播消息
client.on('message', (msg, rinfo) => {
    try {
        const data = JSON.parse(msg.toString());
        console.log('收到服务器广播:', data);
        
        // 如果还没有WebSocket连接，则建立连接
        if (!ws) {
            connectWebSocket(data.serverAddress, data.serverPort);
        }
    } catch (err) {
        console.error('解析消息失败:', err);
    }
});

// 建立WebSocket连接
function connectWebSocket(address, port) {
    ws = new WebSocket(`ws://${address}:${port}`);

    ws.on('open', () => {
        console.log('WebSocket连接已建立');
        // 开始发送心跳
        startHeartbeat();
    });

    ws.on('message', (data) => {
        const message = JSON.parse(data.toString());
        console.log('收到WebSocket消息:', message);

        // 处理心跳响应
        if (message.type === 'heartbeat_response') {
            console.log('收到心跳响应，来自服务器确认的客户端IP:', message.clientIP);
        }
    });

    ws.on('close', () => {
        console.log('WebSocket连接已关闭');
        ws = null;
        // 连接关闭后尝试重新连接
        setTimeout(() => {
            if (!ws) {
                console.log('尝试重新连接...');
                connectWebSocket(address, port);
            }
        }, 5000);
    });

    ws.on('error', (error) => {
        console.error('WebSocket错误:', error);
        ws = null;
    });
}

// 心跳机制
function startHeartbeat() {
    const heartbeat = () => {
        if (ws && ws.readyState === WebSocket.OPEN) {
            const heartbeatMessage = {
                type: 'heartbeat',
                timestamp: new Date().toISOString()
            };
            ws.send(JSON.stringify(heartbeatMessage));
            console.log('已发送心跳');
        }
    };

    // 每5秒发送一次心跳
    const heartbeatInterval = setInterval(heartbeat, 5000);

    // 当连接关闭时清除心跳定时器
    ws.on('close', () => {
        clearInterval(heartbeatInterval);
    });

    // 立即发送第一次心跳
    heartbeat();
}

client.on('error', (err) => {
    console.error('UDP客户端错误:', err);
    client.close();
});

// 处理进程退出
process.on('SIGINT', () => {
    console.log('正在关闭客户端...');
    if (ws) {
        ws.close();
    }
    client.close(() => {
        process.exit(0);
    });
}); 